package cn.tedu.egmvc2.controller;

import cn.tedu.egmvc2.base.response.JsonResult;
import cn.tedu.egmvc2.mapper.UserMapper;
import cn.tedu.egmvc2.pojo.dto.UserAddParam;
import cn.tedu.egmvc2.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc2.pojo.entity.User;
import cn.tedu.egmvc2.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

@Validated
@Slf4j
@RestController
@Api(tags = "01.用户模块")
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.添加用户功能
     * @param userAddParam
     * @return
     */
    @PostMapping("add")
    @ApiOperation("添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult add(@RequestBody @Validated UserAddParam userAddParam){
        log.debug("userAddParam = " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insert(user);

        return JsonResult.ok();
    }

    /**
     * 2.用户列表功能
     */
    @GetMapping("list")
    @ApiOperation("用户列表")
    @ApiOperationSupport(order = 20)
    public JsonResult list(){
        List<UserListVO> userListVOS = userMapper.list();
        System.out.println("userListVOS = " + userListVOS);

        return JsonResult.ok(userListVOS);
    }

    /**
     * 3.删除用户功能
     */
    @PostMapping("del")
    @ApiOperation("删除用户")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "id", value = "用户编号", required = true, dataType = "int")
    public JsonResult del(@Range(min = 1, max = 100, message = "用户编号必须在1-100之间") @RequestParam Integer id){
        log.debug("id = " + id);
        userMapper.delete(id);

        return JsonResult.ok();
    }

    /**
     * 4.更新指定用户功能
     */
    @PostMapping("update")
    @ApiOperation("更新用户")
    @ApiOperationSupport(order = 40)
    public JsonResult update(@ApiIgnore UserUpdateParam userUpdateParam){
        log.debug("userUpdateParam = " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        userMapper.update(user);

        return JsonResult.ok();
    }
}









